#encoding:utf-8

'''
data=2017/1/11 下午4:24
__author__='binpo',
author_email='binpocn@163.com',
'''
import tornado
from logs import LOG
log=LOG('coin')
import json
import hmac
import hashlib
import base64
import datetime
import urllib
import timeit
import sys
stat_time = 0.0
from models import *
PAGE_SIZE = 100
from pagination.page import Paginator
from utils import upload_file,download_file

def hmac_md5(key,args):
    myhmac = hmac.new(key,args, hashlib.md5)
    str_result = base64.b64encode(myhmac.digest())
    return str_result

from concurrent.futures import ThreadPoolExecutor
from functools import partial, wraps

EXECUTOR = ThreadPoolExecutor(max_workers=10)
def unblock(f):

    @tornado.web.asynchronous
    @wraps(f)
    def wrapper(*args, **kwargs):
        self = args[0]
        def callback(future):
            self.write(future.result())
            self.finish()
        EXECUTOR.submit(
            partial(f, *args, **kwargs)
        ).add_done_callback(
            lambda future: tornado.ioloop.IOLoop.instance().add_callback(
                partial(callback, future)))
    return wrapper

class CoinUploadHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('upload_coin.html')
        
    def post(self, *args, **kwargs):
        cover_meta = self.request.files.get('coin_cover')[0]
        file_meta = self.request.files.get('coin_file')[0]
        
        cove_data = upload_file(cover_meta.get('filename'),cover_meta.get('body'))
        file_data = upload_file(file_meta.get('filename'),file_meta.get('body'))
#         print(file_data)
#         print(cove_data)
        echatcoin = EchatCoin()
        echatcoin.filename = file_meta.get('filename')
        echatcoin.file_path = file_data.get('filename')
        echatcoin.title = self.get_argument('title','')
        echatcoin.description = self.get_argument('description','')
        echatcoin.cover = cove_data.get('full_url')
        echatcoin.save()
        self.write('upload success')
        
class CoinDownloadHandler(tornado.web.RequestHandler):

    def check_xsrf_cookie(self):
        pass
    
    def get(self):
        coin_id= self.get_argument('coin_id','')
        if coin_id:
            echat_coin = EchatCoin.select().where(EchatCoin.id==coin_id).get()
            filename=''
            self.set_header('Content-Type', 'application/octet-stream')
            self.set_header('Content-Disposition', 'attachment; filename=' + echat_coin.filename)
            downdata = download_file(echat_coin.file_path)
            self.write(downdata)
        else:
            echat_coin_list = EchatCoin.select().order_by(EchatCoin.pub_date.desc())
            self.render('coin_list.html',coin_list=echat_coin_list)
            
        
   
